package com.laxia.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;

/**
 * 密码处理工具类 密码转成密文保存数据库
 *
 * @author weishuai
 * @since 2019-09-12
 */
public class PasswordUtil {

    private static String DEFAULT_PASSWORD = "123456";

    public static String defaultPassword() {
        return md5(DEFAULT_PASSWORD);
    }


    public static String generatePassword(String password) {
        if (StringUtil.isBlank(password)) {
            return defaultPassword();
        }
        return md5(password);
    }

    public static boolean validPassword(String loginPassword, String dbPassword) {
        return Objects.equals(generatePassword(loginPassword), dbPassword);
    }


    private static String md5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] bytes = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return password;
    }
}
